<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        isScalingBtn
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="460"
        :selection-change="selectionChange"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('批量提交')"
            :loading="batchSubmitLoading"
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            :disabled="!tableInfo.selection.length"
            @click="handleSubmit(tableInfo.selection)"
            >批量提交</el-button
          >
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import {
  FORM_ITEM_LIST,
  initTableColumns,
} from '../constants/notCommit';
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';
import { getSearchParamBySearchType } from '@/utils/getUtils';
import { getBtnsId } from '@/libs/btnsPermission';

export default {
  components: {
    BasicTableForm,
    BasicTable
  },
  data () {
    return {
      batchSubmitLoading: false,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: initTableColumns(this),
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      formData: {
        categoryPath: '',
        spuNo: '',
        productNameFinal: '',
        brandName: '',
        productType: '',
        createOper: ''
      },
      apiObj: {
        // 查询未提交列表
        getPreparingList: {
          url: '/sysback/prepare/list/getPreparingNotCommitList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 提交待准入的单据
        commitByProduct: {
          url: '/sysback/prepare/list/commitByProduct',
          type: 'post' // 接口请求类型
        },
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    this.getTableData();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div class="table-action"><el-button type="text" onClick={() => this.handleSubmit(row)}>提交</el-button></div>;
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableData();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableData();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableData();
    },
    // 勾选需要处理的库存
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // 获取表格数据
    getTableData () {
      const fixedParam = [
        { name: 'belongToDepartmentFlag', value: '1' },
        { name: 'groupFlag', value: '1' } // * 是否是集团总部 0:不是 1:是
      ]
      let data = {
        searchParam: JSON.stringify([...getSearchParamBySearchType(FORM_ITEM_LIST, this.formData), ...fixedParam]),
        ...this.pagination
      };
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableInfo.loading = true;
      ApiRequest(
        this.apiObj.getPreparingList.url,
        this.apiObj.getPreparingList.type,
        data
      ).then((res) => {
        this.tableInfo.loading = false;
        if (res.retStatus === '1') {
          const { results, totalNum } = res.retData;
          this.tableInfo.list = results;
          this.pagination.totalNum = totalNum;
        }
      }).catch(() => {
        this.tableInfo.loading = false;
      });
    },
    // 提交
    handleSubmit (param) {
      let flag = '';
      let productUuids = '';
      if (Array.isArray(param)) {
        let uuidList = param.map((item) => (item.uuid)) || [];
        productUuids = uuidList.join(',');
        flag = judgeAuthDepartmentFn(param);
      } else {
        productUuids = param.uuid;
        flag = judgeAuthDepartmentFn([param]);
      }
      if (!flag) {
        return;
      }
      let data = {
        productUuids
      }
      this.$confirm('确认提交吗？', '提交', {
        type: 'warning',
      }).then(() => {
        this.batchSubmitLoading = true;
        this.tableInfo.loading = true;
        ApiRequest(
          this.apiObj.commitByProduct.url,
          this.apiObj.commitByProduct.type,
          data,
          true
        )
          .then((res) => {
            this.batchSubmitLoading = false;
            this.tableInfo.loading = false;
            if (res.retStatus === '1') {
              this.$Message.success('提交成功');
              this.tableInfo.selection = [];
              this.getTableData();
            }
          })
          .catch(() => {
            this.batchSubmitLoading = false;
            this.tableInfo.loading = false;
          });
      });
    },
  }
};
</script>
